package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyCommentQuery;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMongoRepository repository;
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;

    public void save(StrategyComment entity) {
        //填充创建时间
        entity.setCreateTime(new Date());

        //评论+1操作
        strategyStatsCacheService.incr(entity.getDetailId(), 1, IStrategyStatsCacheService.REPLYNUM_TYPE);

        //使用mongdb的方法做保存
        repository.save(entity);
    }

    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        return repository.findByDetailId(qo.getDetailId(), pageable);
    }

    public void commentThumbUp(String toId, Long fromId) {
        //根据id查评论对象
        Optional<StrategyComment> optional = repository.findById(toId);
        //System.out.println(1/0);
        /**
         * 利用java8新特性做的
         */
        optional.ifPresent(comment -> {
            //取出该评论的点赞列表
            List<Long> thumbuplist = comment.getThumbuplist();
            //判断当前点赞列表是否有当前点赞对象id
            if (thumbuplist.contains(fromId)) {
                //包含->取消点赞
                thumbuplist.remove(fromId);
            } else {
                //不包含->添加点赞
                thumbuplist.add(fromId);
            }
            //设置点赞数
            comment.setThumbupnum(thumbuplist.size());
            //更新该评论
            repository.save(comment);
        });


        /**
         * 老方式做的
         */
        /*if(optional != null){//判断optional这个容器是否为空
           StrategyComment comment = optional.get();//不为空取出容器中的评论对象
           List<Long> thumbuplist = comment.getThumbuplist();//评论对象的集合
           if(thumbuplist.contains(fromId)){//如果评论对象的集合中存在该用户的点赞id
               thumbuplist.remove(fromId);//移除
           }else {
               thumbuplist.add(fromId);//添加
           }
           //设置点赞数
           comment.setThumbupnum(thumbuplist.size());
           //更新该评论
           repository.save(comment);
       }*/

    }
}
